let url_ = `http://api.okzy.org/api.php/provide/vod/at/json`
const db = require("mysql");

function makeDBWhere(search) {
	console.log(search)
	let e = []
	for (let v in search) {
		if (typeof search[v] == 'object') {
			// if (search[v].do == 'like') {
			// } else {
			// }
			e.push(`${v} ${search[v].do} ${search[v].value}`)
		} else if (search[v]) e.push(`${v}=${search[v]}`)
	}
	if (e.length == 0) return ''
	return 'where ' + e.join(' and ')
}

async function setting(key, value, page, size) {
	try {
		if (value) {
			let data = await setting(key)
			if (!data)
				await db.query2(`insert into \`setting\`(\`key_\`,\`value_\`) values(?,?)`, [key, value])
			else
				await db.query2(`update \`setting\` set key_=?,value_=? where key_=?`, [key, value, key])
		} else if (key) {
			let data = (await db.query2(`select value_ from setting where key_=?`, [key]))[0]
			return data.length == 0 ? null : data[0].value_
		} else if (page != null) {
			console.log(page * size, size || 15)
			return (await db.query2(`select * from setting limit ?,?`, [page * size, size || 15]))[0]
		}
	} catch (e) {
		console.error(e)
		return null
	}
	return null
}

async function video(vod_id, value) {
	if (value) {
		let vod_id_ = await video(vod_id)
		let keys = Object.keys(value)
		if (!vod_id_) {
			let sql =
				`insert into \`videos\`(${keys.map(e => `\`${e}\``).join(',')}) values(${keys.map(e => JSON.stringify(value[e])).join(',')})`
			let data = (await db.query2(sql)[0])
		} else {
			let sql =
				`delete from  \`videos\` where vod_id=${vod_id}`
			let data = (await db.query2(sql)[0])
			video(vod_id, value)
		}

	} else if (vod_id) {
		try {
			let data = (await db.query2(`select vod_id from videos where vod_id=?`, [vod_id]))[0]
			return data.length == 0 ? null : data[0].vod_id
		} catch (e) {
			console.error(e)
			return null
		}
	}

	return null
}

async function reqPage(page, h) {
	try {
		const res = await uniCloud.request({
			url: `${url_}?ac=detail&pg=${page}&h=${h||''}`
		})

		console.log(`${url_}?ac=detail&pg=${page}&h=${h||''}`, res.data)
		for (let v of res.data.list) {
			if (!v.vod_id) continue;
			await video(v.vod_id, v)
		}
		return res.data.list
	} catch (e) {
		setTimeout(async function() {
			return await reqPage(page, h)
		}, 5000);
		//TODO handle the exception
	}
}

async function rebuild() {
	let i = setting('itpage') || 1
	console.log(`正在copy ${i}`)
	await reqPage(i)
	i++
	setting('itpage', i)
	return 1
}

async function reClass() {
	const res = await uniCloud.request({
		url: `${url_}?ac=list&t=1&pg=5`
	})
	// console.log(res.data.code)
	if (res.data.code != 1) return
	await setting('class', JSON.stringify(res.data.class))
	return await setting('class')
}

async function videoList(type1, type, page, size, ids) {
	let where = makeDBWhere(!ids ? {
		type_id_1: type1,
		type_id: type
	} : {
		vod_id: {
			do: 'in',
			value: `(${ids.join(',')})`
		}
	})

	if (ids)
		return {
			list: (await db.query2(`select * from videos ${where}`))[0],
			count: ids.length
		}

	let list = (await db.query2(
		`select * from videos ${where} order by vod_time_add desc limit ?,?`,
		[
			(page || 0) * size,
			size || 15
		],
	))[0]

	return {
		list,
		count: parseInt(((await db.query2(
			`select count(1) from videos ${where}`
		))[0][0]['count(1)'] || 0) / size + 0.99)
	}
}

module.exports = {
	reClass,
	setting,
	reqPage,
	video,
	rebuild,
	videoList
}